package com.jt.demo;

import redis.clients.jedis.Jedis;

import java.util.*;

public class SSODemo01 {
    //检查session信息是否有效
    public static Boolean isValidSession(){
        Jedis jedis = new Jedis("192.168.126.129",6379);
        //jedis.auth("123456");
        Map<String, String> map = jedis.hgetAll("session");
        System.out.println("map"+map);
        if (map==null||map.size()==0){
            System.out.println("还没有登录");
            jedis.close();
            return false;
        }
        //3.判定是否登录超时
        String dataStr = map.get("expired");
        if (dataStr==null||"".equals(dataStr)){
            System.out.println("登录超时");
            jedis.close();
            return false;
        }
        Date expired = new Date(Long.valueOf(dataStr));
        if (expired.before(new Date())){
            System.out.println("登录超时");
            jedis.close();
            return false;
        }
        return true;
    };



    //登录操作
    public static void login(String username,String password){
        if (!"123456".equals(password)){
            System.out.println("密码错误");
            return;
        }
        //1.创建token(一般可以用一个随机的字符串)
        String token = UUID.randomUUID().toString().replace("-", "");
        System.out.println(token);
        //2.创建有效时长
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 30);
        //3.存储会话信息
        Map<String,String> map = new HashMap<>();
        map.put(token, username);
        map.put("expired",String.valueOf(calendar.getTimeInMillis()));
        Jedis jedis = new Jedis("192.168.126.129",6379);
        jedis.hset("session", map);
        jedis.close();


    }

    public static void main(String[] args) {
        System.out.println("访问系统资源=======");
        //1.访问redis,检查是否有有效的会话信息
        boolean flag = isValidSession();
        if (flag){
            System.out.println("直接访问");
        }else {
            //2.没有有效的会话信息,创建会话,存储到redis
            login("jack", "123456");


        }

    }

}
